package com.jim.healio.controller;

import com.jim.healio.agents.impl.Archivist;
import com.jim.healio.agents.impl.Chairman;
import com.jim.healio.agents.impl.Doctor;
import com.jim.healio.agents.impl.TestAgent;
import com.jim.healio.dto.History;
import com.jim.healio.dto.Message;
import com.jim.healio.storage.MemoryManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/agent")
public class AgentController {

    private static final Logger logger = LoggerFactory.getLogger(AgentController.class);

    @Autowired
    private MemoryManager memoryManager;

    @Autowired
    private Doctor bob;

    @Autowired
    private Archivist alice;

    @Autowired
    private Chairman john;

    @Autowired
    private TestAgent testAgent;

    @PostMapping("/chat")
    public Message chat(@RequestParam String sessionId, 
                       @RequestParam String role,
                       @RequestParam String name,
                       @RequestParam String content,
                       @RequestParam String receiver) {
        logger.info("收到聊天请求 - SessionId: {}, From: {}({}), To: {}, Content: {}", 
                   sessionId, name, role, receiver, content);
        
        // 创建Message对象
        Message message = new Message(role, name, content, receiver);
        
        // 1. 获取历史记录
        History history = memoryManager.getHistory(sessionId);
        if(history == null) {
            history = new History();
            memoryManager.addHistory(sessionId, history);
        }
        history.addMessage(message);

        // 构建prompt
        String prompt = "当前沟通记录：\n" + history;

        // 2. 调用agent
        Message response = null;
        if(message.getReceiver().equals("Bob")) {
            logger.info("调用Agent Bob处理消息");
            response = bob.invoke(prompt);
        } else if(message.getReceiver().equals("Alice")) {
            logger.info("调用Agent Alice处理消息");
            response = alice.invoke(prompt);
        } else if(message.getReceiver().equals("John")) {
            logger.info("调用Agent John处理消息");
            response = john.invoke(prompt);
        } else {
            logger.warn("未知的接收者: {}", message.getReceiver());
            return null;
        }
        
        if(response != null) {
            logger.info("Agent响应 - From: {}({}), To: {}, Content: {}", 
                       response.getName(), response.getRole(), response.getReceiver(), response.getContent());
        }
        
        return response;
    }

    @GetMapping("/query")
    public Message query(@RequestParam String query) {
        return testAgent.chat(query);
    }
}
